package com.cindata.api

import grails.converters.JSON
import groovy.json.JsonOutput
import groovyx.net.http.ContentType
import groovyx.net.http.FromServer
import groovyx.net.http.OkHttpBuilder

import okhttp3.OkHttpClient
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Value

import java.util.concurrent.TimeUnit

import static groovyx.net.http.util.SslUtils.ignoreSslIssues

class SplitMatchApiService implements InitializingBean
{

    static scope = "singleton"
    OkHttpBuilder http

    @Value('${splitMatchApi.address}')
    String apiAddress
    @Value('${splitMatchApi.splitMatch}')
    String splitMatchAPI

    /**
     * 地址拆分匹配
     * @param city
     * @param address
     * @param count
     * @return
     */
    def splitMatch(String city, String address)
    {
        def result
        try
        {
            result = post(splitMatchAPI, [city: city, address: address])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [],
                message: ex.getMessage()]
        }
        return result
    }

    @Override
    void afterPropertiesSet() throws Exception
    {
        http = OkHttpBuilder.configure {
            if (apiAddress.contains("https"))
            {
                ignoreSslIssues execution
            }
            request.uri = apiAddress
            client.clientCustomizer { OkHttpClient.Builder builder -> builder.connectTimeout(5, TimeUnit.SECONDS)
            }
        }
    }

    def post(String url, Map data)
    {
        try
        {
            http.post {
                request.uri.path = "${url}"
                request.contentType = ContentType.JSON
                if (data)
                {
                    request.body = data
                }
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println "splitMatch:" + resp.statusCode
                    return JSON.parse(json.toString())
                }
                response.failure { resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

    def get(String url, Map data)
    {
        try
        {
            http.get {
                request.uri.path = "${url}"
                request.contentType = ContentType.JSON
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    return JSON.parse(json.toString())
                }
                response.failure { FromServer resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }
}
